<template>
  <div>
    <button @click="fetchData">加载数据</button>
    <div id="main" style="width: 600px; height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      chart: null,
      dates: [],
      amounts: []
    };
  },
  methods: {
    fetchData() {
      fetch('http://localhost:3000/data')
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          this.dates = data.map(item => item.date);
          this.amounts = data.map(item => item.amount);
          this.drawChart();
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    },
    drawChart() {
      if (!this.chart) {
        this.chart = echarts.init(document.getElementById('main'));
      }

      const option = {
        xAxis: {
          type: 'category',
          data: this.dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.amounts,
          type: 'line'
        }]
      };

      this.chart.setOption(option);
    }
  },
  mounted() {
    this.drawChart();  // 初始化时绘制空图表
  }
};
</script>

<style>
/* 可选：添加一些样式 */
</style>
